package cn.signalpha.common.wechat.handler;

import cn.signalpha.core.tool.utils.ObjectUtil;
import cn.signalpha.modules.base.entity.WxReplyRule;
import cn.signalpha.modules.base.service.WxReplyRuleService;
import cn.signalpha.modules.com.entity.UserOauth;
import cn.signalpha.modules.com.entity.enums.UserSourceEnum;
import cn.signalpha.modules.com.service.UserOauthService;
import cn.signalpha.modules.com.service.UserService;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author Binary Wang(https://github.com/binarywang)
 */
@Slf4j
@Component
@AllArgsConstructor
public class SubscribeHandler extends AbstractHandler {

	private final UserService userService;
	private final UserOauthService userOauthService;
	private final WxReplyRuleService wxReplyRuleService;

	@Override
	public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
									Map<String, Object> context, WxMpService weixinService,
									WxSessionManager sessionManager) throws WxErrorException {
		// 用户关注事件
		try {
			log.info("触发用户关注事件：{}", wxMessage.getFromUser());
			WxMpUser userWxInfo = weixinService.getUserService().userInfo(wxMessage.getFromUser(), null);
			if (userWxInfo != null) {
				log.info("userWxInfo：{}", userWxInfo);
				UserOauth userOauth = userOauthService.getByOpenIdAndSource(userWxInfo.getOpenId(), UserSourceEnum.WECHAT_PUBLIC.getValue());
				if(ObjectUtil.isNotEmpty(userOauth)){
					//更新关注状态
					userOauthService.updateById(UserOauth.builder().id(userOauth.getId()).status(1).build());
					userOauthService.removeCaCheByOpenIdAndSource(userOauth.getOpenId(), userOauth.getSource());
				}else{
					//新用户入库
					userOauth = new UserOauth();
					userOauth.setAppId(weixinService.getWxMpConfigStorage().getAppId());
					userOauth.setSource(UserSourceEnum.WECHAT_PUBLIC.getValue());
					userOauth.setOpenId(userWxInfo.getOpenId());
					userOauth.setUnionId(userWxInfo.getUnionId());
					userOauth.setStatus(1);
					userService.userInfo(userOauth);
				}
			}
		} catch (WxErrorException e) {
			if (e.getError().getErrorCode() == 48001) {
				this.logger.info("该公众号没有获取用户信息权限！");
			}
		}

		WxReplyRule wxReplyRule = wxReplyRuleService.getOne(Wrappers.<WxReplyRule>lambdaQuery().eq(WxReplyRule::getType, 1).eq(WxReplyRule::getStatus, 1).orderByDesc(WxReplyRule::getSort).last("limit 1"));
		if(ObjectUtil.isNotEmpty(wxReplyRule)){
			wxReplyRuleService.reply(wxMessage.getFromUser(), wxReplyRule.getReplyType(), wxReplyRule.getReplyValue());
		}
		WxMpXmlOutMessage responseResult = null;
		try {
			responseResult = this.handleSpecial(wxMessage);
		} catch (Exception e) {
			this.logger.error(e.getMessage(), e);
		}
		return responseResult;
	}

    /**
     * 处理特殊请求，比如如果是扫码进来的，可以做相应处理
     */
    private WxMpXmlOutMessage handleSpecial(WxMpXmlMessage wxMessage)
        throws Exception {
        //TODO
        return null;
    }

}
